package keter.lab.grpc.cloud.controllers;

import com.alibaba.fastjson.JSONObject;
import keter.lab.grpc.cloud.PerfData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

@RestController
@RequestMapping("/perf/http")
public class PerfController {
	private static final Logger logger = LoggerFactory.getLogger(PerfController.class);

	@Autowired
	PerfData data;
	/**
	 * 为client调用提供基准性能测试
	 * @return
	 */
	@GetMapping("/basic")
	public String http() {
		return "hello world!";
	}

	@GetMapping("/basic/jsonobject")
	public JSONObject basicJsonObject() {
		JSONObject jsonObject = JSONObject.parseObject("{\"name\":'haha',\"count\":1}");
		return jsonObject;
	}

	@GetMapping("/bigjsonstring")
	public String bigJson() throws IOException {
		return data.bigJsonString();
	}

	@GetMapping(value = "/bigjsonstring/gzip", produces = "text/compressed;charset=ISO-8859-1")
	public String bigJsonGzip(HttpServletRequest request) throws IOException {
		logger.info("headers:{}",request.getHeader("Accept-Encoding"));
		String content = data.bigJsonString();
		return getISOString(content);
	}

	@GetMapping("/jsonobj")
	public JSONObject jsonObj(){
		return data.jsonObjectData();
	}


	private String getISOString(String s) throws UnsupportedEncodingException {
		return new String(s.getBytes(), "ISO-8859-1");
	}
}
